<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '个人资料',
  },
}
</route>

<script setup lang="ts">
import type { ProfileDetailRespVO, ProfileUpdateReqVO } from '@/types/profile'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import {
  getUserDetailInfo,
  handleProfileError,
  processAvatarUrl,
  updateUserInfo,
  validatePhone,
} from '@/api/profile'

// 获取状态栏高度
const statusBarHeight = ref(0)

// 表单引用
const formRef = ref()

// 状态管理
const loading = ref(false)
const saving = ref(false)
const uploading = ref(false)

// 表单数据
const formData = reactive({
  avatar: '',
  nickname: '',
  phone: '',
})

// 原始数据（用于比较是否有变更）
const originalData = ref<ProfileDetailRespVO | null>(null)

// 表单验证规则
const formRules = {
  nickname: {
    rules: [
      { required: true, errorMessage: '请输入昵称' },
      { minLength: 1, maxLength: 20, errorMessage: '昵称长度为1-20个字符' },
    ],
  },
  // 注释掉手机号验证规则
  // phone: {
  //   rules: [
  //     {
  //       validateFunction: (rule: any, value: string, data: any, callback: Function) => {
  //         if (value && !validatePhone(value)) {
  //           callback('请输入正确的手机号')
  //         }
  //         return true
  //       },
  //     },
  //   ],
  // },
}

// 加载用户详细信息
async function loadUserInfo() {
  try {
    loading.value = true

    const response = await getUserDetailInfo()
    if (response.code === 0 && response.data) {
      const userInfo = response.data
      originalData.value = userInfo

      // 填充表单数据
      formData.avatar = userInfo.avatar || ''
      formData.nickname = userInfo.nickname || ''
      formData.phone = userInfo.phone || ''
    }
  }
  catch (error) {
    console.error('加载用户信息失败:', error)
    uni.showToast({
      title: handleProfileError(error),
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}

// 验证图片文件
function validateImageFile(filePath: string): Promise<boolean> {
  return new Promise((resolve) => {
    uni.getImageInfo({
      src: filePath,
      success: (res) => {
        // 检查图片尺寸
        if (res.width > 2000 || res.height > 2000) {
          uni.showToast({
            title: '图片尺寸过大，建议使用800x800以下的图片',
            icon: 'none',
          })
          resolve(false)
          return
        }

        resolve(true)
      },
      fail: (error) => {
        console.error('获取图片信息失败:', error)
        uni.showToast({
          title: '图片格式不支持',
          icon: 'none',
        })
        resolve(false)
      },
    })
  })
}

// 选择头像
function chooseAvatar() {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]

      // 验证文件
      const isValid = await validateImageFile(tempFilePath)
      if (isValid) {
        uploadAvatar(tempFilePath)
      }
    },
    fail: (error) => {
      console.error('选择图片失败:', error)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none',
      })
    },
  })
}

// 上传头像
async function uploadAvatar(filePath: string) {
  try {
    uploading.value = true

    // 显示上传进度
    uni.showLoading({
      title: '上传中...',
    })

    // 使用uni.uploadFile进行文件上传
    const uploadTask = uni.uploadFile({
      url: '/reading/profile/avatar',
      filePath,
      name: 'avatar',
      header: {
        Authorization: `Bearer ${uni.getStorageSync('token') || ''}`,
      },
      success: (uploadRes) => {
        try {
          console.log('上传响应原始数据:', uploadRes.data)
          const result = JSON.parse(uploadRes.data)
          console.log('解析后的响应数据:', result)

          if (result.code === 0 && result.data) {
            formData.avatar = result.data.avatarUrl
            console.log('头像URL设置为:', result.data.avatarUrl)
            uni.showToast({
              title: '头像上传成功，请点击保存',
              icon: 'success',
            })
          }
          else {
            console.error('上传失败，响应码:', result.code, '消息:', result.msg)
            throw new Error(result.msg || result.message || '上传失败')
          }
        }
        catch (parseError) {
          console.error('解析上传结果失败:', parseError)
          console.error('原始响应数据:', uploadRes.data)
          uni.showToast({
            title: '上传失败',
            icon: 'none',
          })
        }
      },
      fail: (error) => {
        console.error('头像上传失败:', error)
        uni.showToast({
          title: '上传失败，请重试',
          icon: 'none',
        })
      },
      complete: () => {
        uploading.value = false
        uni.hideLoading()
      },
    })

    // 监听上传进度
    uploadTask.onProgressUpdate((res) => {
      console.log('上传进度:', res.progress)
      // 可以在这里更新进度条
    })
  }
  catch (error) {
    console.error('头像上传失败:', error)
    uni.showToast({
      title: handleProfileError(error),
      icon: 'none',
    })
    uploading.value = false
    uni.hideLoading()
  }
}

// 获取头像URL
function getAvatarUrl() {
  return formData.avatar ? processAvatarUrl(formData.avatar) : ''
}

// 检查数据是否有变更
function hasDataChanged() {
  if (!originalData.value)
    return true

  return (
    formData.nickname !== (originalData.value.nickname || '')
    || formData.phone !== (originalData.value.phone || '')
    || formData.avatar !== (originalData.value.avatar || '')
  )
}

// 保存用户信息
async function saveProfile() {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) {
      return
    }

    // 检查是否有变更
    if (!hasDataChanged()) {
      uni.showToast({
        title: '没有修改内容',
        icon: 'none',
      })
      return
    }

    saving.value = true

    // 准备更新数据
    const updateData: ProfileUpdateReqVO = {
      avatar: formData.avatar || undefined,
      nickname: formData.nickname,
      // phone: formData.phone || undefined, // 注释掉手机号更新
    }

    const response = await updateUserInfo(updateData)
    if (response.code === 0) {
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      })

      // 延迟返回，让用户看到成功提示
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  }
  catch (error) {
    console.error('保存失败:', error)
    uni.showToast({
      title: handleProfileError(error),
      icon: 'none',
    })
  }
  finally {
    saving.value = false
  }
}

// 返回上一页
function goBack() {
  if (hasDataChanged()) {
    uni.showModal({
      title: '提示',
      content: '您有未保存的修改，确定要离开吗？',
      success: (res) => {
        if (res.confirm) {
          uni.navigateBack()
        }
      },
    })
  }
  else {
    uni.navigateBack()
  }
}

onLoad(() => {
  // 获取状态栏高度
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0

  loadUserInfo()
})
</script>

<template>
  <view class="profile-edit-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: `${statusBarHeight}px` }">
      <view class="navbar-content">
        <view class="navbar-left" @click="goBack">
          <uni-icons type="left" size="20" color="#333" />
          <text class="back-text">
            返回
          </text>
        </view>
        <view class="navbar-title">
          <text class="title-text">
            个人资料
          </text>
        </view>
        <view class="navbar-right" />
      </view>
    </view>

    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading-container">
        <uni-load-more status="loading" />
      </view>

      <!-- 编辑表单 -->
      <view v-else class="form-container">
        <!-- 个人信息卡片 -->
        <view class="profile-card">
          <!-- 头像上传 -->
          <view class="avatar-upload">
            <view class="avatar-preview" @click="chooseAvatar">
              <image
                v-if="formData.avatar"
                :src="getAvatarUrl()"
                mode="aspectFill"
                class="avatar-image"
              />
              <view v-else class="avatar-placeholder">
                <uni-icons type="camera" size="30" color="#667eea" />
                <text class="placeholder-text">
                  点击上传头像
                </text>
              </view>
            </view>
            <view class="avatar-tips">
              <text>支持JPG、PNG、GIF格式，大小不超过2MB</text>
            </view>
          </view>

          <!-- 表单输入 -->
          <uni-forms ref="formRef" :model="formData" :rules="formRules" label-width="80px">
            <!-- 昵称 -->
            <uni-forms-item label="昵称" name="nickname" required>
              <uni-easyinput
                v-model="formData.nickname"
                placeholder="请输入昵称"
                :maxlength="20"
                :clearable="true"
              />
            </uni-forms-item>

            <!-- 注释掉手机号编辑 -->
            <!-- <uni-forms-item label="手机号" name="phone">
              <uni-easyinput
                v-model="formData.phone"
                placeholder="请输入手机号"
                type="number"
                :maxlength="11"
                :clearable="true"
              />
            </uni-forms-item> -->
          </uni-forms>
        </view>

        <!-- 保存按钮 -->
        <view class="save-button-container">
          <button class="save-btn" :disabled="saving" @click="saveProfile">
            {{ saving ? '保存中...' : '保存' }}
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.profile-edit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: relative;
}

/* 自定义导航栏 */
.custom-navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);

  .navbar-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 44px;
    padding: 0 15px;

    .navbar-left {
      display: flex;
      align-items: center;
      gap: 5px;
      cursor: pointer;

      .back-text {
        font-size: 16px;
        color: #333;
      }
    }

    .navbar-title {
      flex: 1;
      text-align: center;

      .title-text {
        font-size: 18px;
        font-weight: 600;
        color: #333;
      }
    }

    .navbar-right {
      width: 60px;
    }
  }
}

/* 页面内容 */
.page-content {
  padding-top: 60px;
  min-height: 100vh;
  background: #f8f9fa;
  border-radius: 20px 20px 0 0;
  margin-top: 20px;
}

.loading-container {
  padding: 50px 20px;
  text-align: center;
}

.form-container {
  padding: 30px 20px;
}

/* 个人信息卡片 */
.profile-card {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  border-radius: 20px;
  padding: 30px 20px;
  box-shadow: 0 8px 32px rgba(102, 126, 234, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  margin-bottom: 30px;
}

/* 头像上传 */
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;

  .avatar-preview {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    border: 3px solid #667eea;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.3);
    transition: all 0.3s ease;
    cursor: pointer;

    &:active {
      transform: scale(0.95);
    }

    .avatar-image {
      width: 100%;
      height: 100%;
      border-radius: 50%;
    }

    .avatar-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      .placeholder-text {
        font-size: 12px;
        color: #667eea;
        margin-top: 8px;
        font-weight: 500;
      }
    }
  }

  .avatar-tips {
    margin-top: 15px;

    text {
      font-size: 12px;
      color: #999;
    }
  }
}

/* 保存按钮 */
.save-button-container {
  margin-top: 20px;
  padding: 0 20px 10px;

  .save-btn {
    width: 100%;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 25px;
    padding: 5px 20px;
    font-size: 18px;
    font-weight: 600;
    box-shadow: 0 8px 32px rgba(102, 126, 234, 0.4);
    transition: all 0.3s ease;

    &:disabled {
      opacity: 0.6;
      transform: none;
    }

    &:not(:disabled):active {
      transform: translateY(2px);
      box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
    }
  }
}

/* 表单样式优化 */
.profile-card :deep(.uni-forms-item) {
  margin-bottom: 20px;
  // background: rgba(102, 126, 234, 0.05);
  border-radius: 12px;
  padding: 15px;
  // border: 1px solid rgba(102, 126, 234, 0.1);

  .uni-forms-item__label {
    font-weight: 600;
    color: #333;
    font-size: 15px;
    margin-bottom: 8px;
  }

  .uni-easyinput {
    border-radius: 8px;

    .uni-easyinput__content {
      border-radius: 8px;
      border: 1px solid #e0e6ff;
      background: rgba(255, 255, 255, 0.9);
      transition: all 0.3s ease;

      &.is-focused {
        border-color: #667eea;
        background: rgba(255, 255, 255, 1);
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
      }
    }

    .uni-easyinput__content-input {
      font-size: 15px;
      color: #333;
    }
  }
}

/* 响应式设计 */
@media (max-width: 375px) {
  .form-container {
    padding: 20px 15px;
  }

  .avatar-upload .avatar-preview {
    width: 100px;
    height: 100px;
  }

  .save-button-container {
    padding: 0 15px 20px;

    .save-btn {
      padding: 14px 25px;
      font-size: 16px;
    }
  }

  :deep(.uni-forms-item) {
    padding: 15px;
    margin-bottom: 20px;
  }
}
</style>
